package com.flycms.utils;

import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/9/17 14:37
 */
public class SignUtil {
    private final static Integer MAX_LENGTH = 32;
    public final static String CLIENT_ID = "l266hw2qztua4nx9";
    private final static String CLIENT_SECRET = "b42fecdab7de4fbf8bc3924f77487d42";
    public static String signQuery(String query) {
        StringBuilder builder = new StringBuilder();
        if(StringUtils.isNotEmpty(query)) {
            builder.append(query);
            builder.append("&");
        }
        builder.append("client_id=").append(CLIENT_ID);
        builder.append("&ts=").append(System.currentTimeMillis());
        builder.append("&sign=").append(getSign(queryToMap(builder.toString())));
        return builder.toString();
    }

    private static String getSign(Map<String, String> params) {
        if(StringUtils.isEmpty(SignUtil.CLIENT_SECRET) || params == null || params.size() == 0){
            return "";
        }
        List<String> paramNames = new ArrayList<>(params.keySet());
        Collections.sort(paramNames);
        StringBuilder builder = new StringBuilder();
        for(String name : paramNames) {
            builder.append(name);
            builder.append("=");
            builder.append(params.get(name));
        }
        builder.append(SignUtil.CLIENT_SECRET);
        try {
            return md5(builder.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    private static Map<String,String> queryToMap(String query) {
        Map<String,String> map = new HashMap<>(16);
        if(StringUtils.isEmpty(query)){
            return map;
        }
        String[] array = query.split("&");
        for(String item : array) {
            String[] p = item.split("=");
            if(p.length == 2){
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    private static String md5(String data) throws NoSuchAlgorithmException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(data.getBytes(Charset.forName("UTF-8")));
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String result = bigInt.toString(16);
        if (result.length() < MAX_LENGTH) {
            StringBuilder buffer = new StringBuilder(result);
            while (buffer.length() < MAX_LENGTH) {
                buffer.insert(0, '0');
            }
            result = buffer.toString();
        }
        return result;
    }

}